package com.gitee.wsl.platform.func.executor.sample

import android.os.Handler
import android.os.Looper
import com.gitee.wsl.concurrent.executor.Executor
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

/** A work runner that uses a [Looper] to run work.  */
open class LooperExecutor internal constructor(looper: Looper) : Executor {
    private val handler: Handler = Handler(looper)

    override var isDisposed: Boolean = false

    private val lock = ReentrantLock()

    /** Will cancel all Runnables posted to this looper.  */
    override fun dispose() {
        lock.withLock {
            handler.removeCallbacksAndMessages(null)
            isDisposed = true
        }
    }

    /**
     * Will post the provided runnable to the looper for processing.
     *
     * @param runnable the runnable you would like to execute
     */
    override fun exec(runnable: Runnable) {
        lock.withLock {
            if (isDisposed) return
            handler.post(runnable)
        }
    }

    companion object {
    }
}
/**
 * Creates a [WorkRunner] backed by the provided [Looper]
 *
 * @param looper the looper to use for processing work
 * @return a [WorkRunner] that uses the provided [Looper] for processing work
 */
fun Executor.Companion.usingLooper(looper: Looper): Executor {
    return LooperExecutor(looper)
}
